package com.lzz.bottomencapsulation.manager;

import android.app.DownloadManager;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import com.lzz.bottomencapsulation.consts.Consts;
import com.lzz.bottomencapsulation.entity.VersionEntity;
import com.lzz.bottomencapsulation.utils.AppUtils;
import com.lzz.bottomencapsulation.utils.FileUtils;
import com.lzz.bottomencapsulation.utils.SPUtils;

/***
 @package ${package}
 @filename ${下载并升级APP}
 */
public class DownloadApkManage {
    public static DownloadApkManage downloadApkManage;
    public static DownloadApkManage getInstance() {
        if (downloadApkManage==null){
            downloadApkManage=new DownloadApkManage();
        }
        return downloadApkManage;
    }

    /**
     * 下载APK
     * @param context
     * @param versionEntity   需要升级的版本信息
     */
    public void downloadAPK(Context context, VersionEntity versionEntity){
        VersionEntity downloadApk=SPUtils.getdownloadAPK();
        if (downloadApk!=null){
            if (downloadApk.getVersion().equals(versionEntity.getVersion())){//安装
                String serviceString = Context.DOWNLOAD_SERVICE;
                DownloadManager dManager = (DownloadManager) context.getSystemService(serviceString);
                if (DownloadManager.STATUS_SUCCESSFUL==queryDownloadAPK(dManager,downloadApk.getDwonloadID())){
                    if (FileUtils.installApk(dManager.getUriForDownloadedFile(downloadApk.getDwonloadID()), context)) return;
                }
                else if (DownloadManager.STATUS_RUNNING==queryDownloadAPK(dManager,downloadApk.getDwonloadID())){
                    return;
                }
            }
        }
        DownloadManager downloadManager= (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri=Uri.parse(versionEntity.getUrl());
        DownloadManager.Request request=new DownloadManager.Request(uri);
        // 设置下载路径和文件名
        request.setDestinationInExternalPublicDir(Consts.ApkPath, AppUtils.getAppName(context) +versionEntity.getVersion()+Consts.Apk);
        request.setDescription("软件新版本下载");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setMimeType("application/vnd.android.package-archive");
        // 设置为可被媒体扫描器找到
        request.allowScanningByMediaScanner();
        // 设置为可见和可管理
        request.setVisibleInDownloadsUi(true);
        // 获取此次下载的ID
        long downloadId= downloadManager.enqueue(request);
//          设置下载标识
        versionEntity.setDwonloadID(downloadId);
//        存储下载apk的信息
        SPUtils.savedownloadAPK(versionEntity);
    }

    /**
     * 查询下载状态
     */
    private int queryDownloadAPK(DownloadManager dManager,long downloadId){
        int state=0;
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor c = dManager.query(query);
        if (c != null && c.moveToFirst()) {
            state = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
//            switch (status) {
//                case DownloadManager.STATUS_PENDING:
//                    state=DownloadManager.STATUS_PENDING;
//                    break;
//                case DownloadManager.STATUS_PAUSED:
//                    state=DownloadManager.STATUS_PAUSED;
//                    break;
//                case DownloadManager.STATUS_RUNNING:
//                    state=DownloadManager.STATUS_RUNNING;
//                    break;
//                case DownloadManager.STATUS_SUCCESSFUL:
//                    state=DownloadManager.STATUS_SUCCESSFUL;
//                    break;
//                case DownloadManager.STATUS_FAILED:
//                    state=DownloadManager.STATUS_FAILED;
//                    break;
//            }
            if (c != null) {
                c.close();
            }
        }
        return state;
    }

    /**
     * 查询下载状态
     */
    public int ifDownload(Context context,long downloadId){
        DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        return queryDownloadAPK(dManager,downloadId);
    }

    /**
     * 安装
     * @param downloadApk
     * @return
     */
    public boolean installApk(Context context,VersionEntity downloadApk){
        if (downloadApk!=null){
            DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            if (DownloadManager.STATUS_SUCCESSFUL==queryDownloadAPK(dManager,downloadApk.getDwonloadID())){
                return FileUtils.installApk(dManager.getUriForDownloadedFile(downloadApk.getDwonloadID()), context);
            }
        }
        return false;
    }

}
